package com.hy.convenient.config.shior;

import com.hy.convenient.common.CommonData;
import com.hy.convenient.common.CommonRegex;
import com.hy.convenient.pojo.login.RolesPermissionsPojo;
import com.hy.convenient.pojo.login.UsersPojo;
import com.hy.convenient.pojo.login.UsersRolePojo;
import com.hy.convenient.service.login.RolesPermissionsService;
import com.hy.convenient.service.login.UsersRoleService;
import com.hy.convenient.service.login.UsersService;
import com.hy.convenient.tool.RedisUitl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private UsersService usersMapper;
    @Autowired
    private RolesPermissionsService rolesPermissions;
    @Autowired
    private RedisUitl redisUitl;
    @Autowired
    private UsersRoleService usersRoleService;

    /**
     * 一些方法需要修改
     * 添加redis的写法
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用权限认证");
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setTimeout(CommonData.EXPIRETIME_1_HOUR * 1000);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Object principal = principalCollection.getPrimaryPrincipal();
        if (principal instanceof UsersPojo) {
            //刷新缓存
            UsersPojo userLogin = (UsersPojo) principal;
            redisUitl.expire(subject.getSession().getId().toString());
            Map<String, Object> map = new HashMap<>();
            map.put("id", userLogin.getRoleId());
            map.put("merid", userLogin.getMerId());
            UsersRolePojo us = usersRoleService.queryAll(map).get(0);
            map.clear();
            map.put("merid",us.getMerid());
            map.put("rolename",us.getRoleName());
            RolesPermissionsPojo rolesPermissionsPojo = rolesPermissions.queryAll(map).get(0);
            info.addStringPermissions(Arrays.stream(rolesPermissionsPojo.getPermission().split(CommonRegex.COMMA)).collect(Collectors.toSet()));
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("-------身份认证方法--------");
        String userId = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("userPass", password);
        UsersPojo user = usersMapper.queryByLogin(map);
        //根据用户名从数据库获取密码
        if (userId == null) {
            throw new AccountException("用户名不正确");
        } else if (!password.equals(user.getUserPass())) {
            throw new AccountException("密码不正确");
        }
        return new SimpleAuthenticationInfo(user, user.getUserPass(), getName());
    }
}
